package com.ihr360.rest.convertor;

import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.ihr360.rest.serializer.fastjson.EnumDataFilter;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public final class JSONHttpMessageConverter {

    public static FastJsonHttpMessageConverter getFastJsonHttpConverter(List<SerializeFilter> filters) {

        //1.需要先定义一个convert消息转换的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.添加fastJson的配置信息,比如:要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        List<SerializeFilter> filterList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(filters)) {
            filterList.addAll(filters);
        }
        List<SerializeFilter> defaultFilterList = defaultValueFilters();
        //Add Common Filter after outside filters
        if (!CollectionUtils.isEmpty(defaultFilterList)) {
            filterList.addAll(defaultFilterList);
        }

        SerializeFilter[] filterArray = new SerializeFilter[filterList.size()];
        filterList.toArray(filterArray);
        fastJsonConfig.setSerializeFilters(filterArray);

        //3.处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //4.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        return fastConverter;
    }

    private static List<SerializeFilter> defaultValueFilters() {
        return Arrays.asList(new EnumDataFilter());
    }

}